package com.wlstock.funi.runnable;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import com.wlstock.funi.R;
import com.wlstock.funi.app.FundApplication;
import com.wlstock.funi.app.FundAsyTask;
import com.wlstock.funi.app.FundAsyTask.TaskLitener;
import com.wlstock.funi.utils.IOUtils;
import com.wlstock.funi.utils.NotiIdGenerator;
import com.wlstock.funi.utils.NotiUtils;
import com.wlstock.funi.utils.ToastUtils;

public class CancelOrder {
	
	private int orderNum;
	private ArrayList<Integer> orderNums;
	private String params;
	
	public enum CANCEL_CODE{
		CANCEL_OK,
		CANCEL_ERROR
	}
	
	public void reqCancel(int orderNum, onCancelListener listener){
		params = "?orderid="+orderNum+";;";
		reqCancel(listener);
	}
	
	public void reqCancel(ArrayList<Integer> orderNums, onCancelListener listener){
		params = getParams(orderNums);
		reqCancel(listener);
	}
	
	/**
	 * 获取参数
	 * @return
	 */
	private String getParams(ArrayList<Integer> nums) {
		String params = "?orderid=";
		for(int i = 0 ; i < nums.size() ; i++ ){
			params = params + nums.get(i)+";;";
		}
		return params;
	}

	private void reqCancel(final onCancelListener listener){
		if (!FundApplication.isLogSuccess) {
			NotiUtils.showSimpleNoti(FundApplication.getInstance(), NotiIdGenerator.ID_LOG_OUTDATE, "登陆失效，请重新登陆", "无法获取最新价格", R.drawable.ic_exception);
			ToastUtils.showMiddleMsg(FundApplication.getInstance(), "尚未登录，无法获取最新价格");
			return;
		}
		
		StringBuffer sb = new StringBuffer();
		sb.append("https://etrade.cs.ecitic.com/ymtrade/trade/stockAction.do?method=entrustCancelOrder"+params);
		FundAsyTask<String, Void, Void> task = new FundAsyTask<String, Void, Void>();
		task.backListener = new TaskLitener<String, Void>() {

			@Override
			public Void doInBackground(String... params) {
				HttpClient client = new DefaultHttpClient();
				
				HttpGet hGet = new HttpGet(params[0]);
				hGet.addHeader("Accept","application/json, text/javascript, */*");
				hGet.addHeader("Accept-Encoding","gzip, deflate");
				hGet.addHeader("Content-Length","15");
				hGet.addHeader("Accept-Language","zh-CN,zh;q=0.8,en;q=0.6");
				hGet.addHeader("Connection","keep-alive");
				hGet.addHeader("Content-Type","application/x-www-form-urlencoded");
				hGet.addHeader("Cookie",FundApplication.cookie);
				hGet.addHeader("Host","etrade.cs.ecitic.com");
				hGet.addHeader("Origin","https://etrade.cs.ecitic.com");
				hGet.addHeader("Referer","https://etrade.cs.ecitic.com/ymtrade/stock/cancel.jsp");
				hGet.addHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.86 Safari/537.36");
				hGet.addHeader("X-Requested-With","XMLHttpRequest");

				try {
					HttpResponse response = client.execute(hGet);
					
					if (response.getStatusLine().getStatusCode() == 200) {
//						{cssweb_type:'error',cssweb_msg:'撤单未成功：<br/>6:网络错误<br/>'}
//						{cssweb_type:'success',cssweb_msg:'撤单委托已提交，请查询当日委托查看是否撤单成功'}
						
						String result = IOUtils.is2Str(response.getEntity().getContent());
						JSONObject obj = new JSONObject(result);
						if ("success".equals(obj.opt("cssweb_type"))) {
							listener.cancel(CANCEL_CODE.CANCEL_OK, "撤单成功");
						} else {
							listener.cancel(CANCEL_CODE.CANCEL_ERROR, (String) (obj.opt("cssweb_msg")!=null?obj.opt("cssweb_msg"):"撤单失败"));
						}
					}
					
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();	
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} finally{
					client.getConnectionManager().shutdown();
				}
				return null;
			}
		};
		task.execute(sb.toString());
		
	}

	public interface onCancelListener{
		public void cancel(CANCEL_CODE code,String msg);
	}
	
}
